<?php
/**
 * V7 checke 1
 * 
 * @author Leon
 */
class data_social extends data {
	public function __construct() {
		parent::__construct();
	}
	/**
	 * 根据type返回不同的社交网站的登陆授权网址
	 * 
	 * @param String $social_type
	 * @param String $flag			// iframe / setting
	 * @return String
	 */
	public static function get_authorize_url ($social_type, $flag='iframe/setting') {
		switch ($social_type) {
			case 'weibo':
				$data_weibo = new data_weibo();
				return $data_weibo->authorize_url($flag);
				break;
			case 'renren':
				$data_renren = new data_renren();
				return $data_renren->authorize_url($flag);
				break;
			case 'kaixin001':
				$data_kaixin001 = new data_kaixin001();
				return $data_kaixin001->authorize_url($flag);
				break;
			case 'qqwb':
				$data_qqwb = new data_qqwb();
				return $data_qqwb->authorize_url($flag);
				break;
			default :
				return false;
		}
	}
	/**
	 * 去API用code换取token
	 * 
	 * @param type $social_type
	 * @param type $code
	 * @return array (uid, access_token, refresh_token, ctime, expires_in, name, nick)
	 */
	public static function code_to_token ($social_type, $code) {
		switch ($social_type) {
			case 'weibo':
				$data_weibo = new data_weibo();
				return $data_weibo->code_2_token($code);
				break;
			case 'renren':
				$data_renren = new data_renren();
				return $data_renren->code_2_token($code);
				break;
			case 'kaixin001':
				$data_kaixin001 = new data_kaixin001();
				return $data_kaixin001->code_2_token($code);
				break;
			case 'qqwb':
				$data_qqwb = new data_qqwb();
				return $data_qqwb->code_2_token($code);
				break;
			default :
				return false;
		}
	}

	public static function make_callback_url () {
		return 'http://uread.me/callback.php';
	}
	// 用state传递一个用户的唯一标示,这个标示在调转到rediret_uri时会被原样返回
	public static function make_state ($social_type, $flag = 'iframe/setting') {
		// 根据账号的类型设定第一位
		switch ($social_type) {
			case 'weibo':	$a = '1';	break;
			case 'renren':	$a = '2';	break;
			case 'kaixin001':	$a = '3';	break;
			case 'qqwb':	$a = '4';	break;
			default:		return false;
		}
		// 根据返回后的操作设定第二位
		switch ($flag) {
			case 'iframe':	$b = '1';	break;
			case 'setting':	$b = '2';	break;
			default :		$b = '0';
		}
		// 把md5放在第三位
		if (empty($_SESSION['state'])) {
			$_SESSION['state'] = md5(microtime());
		}
		return $a . $b . $_SESSION['state'];
	}
	public static function check_state ($state) {
		if ($state) {
			$a = substr($state, 0, 1);
			$b = substr($state, 1, 1);
			$c = substr($state, 2, 32);
			if ($state and $c == $_SESSION['state']) {
				self::clear_state();
				switch ($a) {
					case '1':	$return['social_type'] = 'weibo';	break;
					case '2':	$return['social_type'] = 'renren';	break;
					case '3':	$return['social_type'] = 'kaixin001';	break;
					case '4':	$return['social_type'] = 'qqwb';	break;
					default:	return false;
				}
				switch ($b) {
					case '1':	$return['flag'] = 'iframe';	break;
					case '2':	$return['flag'] = 'setting';	break;
				}
				return $return ;
			} else {
				new data_error_devel('check state 错误', array('session'=>$_SESSION, 'state'=>$state), __CLASS__, __FUNCTION__, __LINE__);
				return false;
			}
		} else return false;
	}
	public static function clear_state () {
		unset($_SESSION['state']);
	}
	
	public static function make_recommend_id ($social_type, $article_id) {
		$article_id = intval($article_id);
		
		if ($article_id) {
			switch ($social_type) {
				case 'weibo':
					return '1' . $article_id;
					break;
				case 'renren':
					return '2' . $article_id;
					break;
				case 'kaixin001':
					return '3' . $article_id;
					break;
				case 'qqwb':
					return '4' . $article_id;
					break;
				default :
					return false;
			}
		} else return false;
	}
	public static function parse_recommend_id ($recommend_id_at_home) {
		if (preg_match('/^\d+$/', $recommend_id_at_home)) {
			$frist_char = substr($recommend_id_at_home, 0, 1);
			switch ($frist_char) {
				case '1':
					return array ('social_type' => 'weibo', 'article_id' => substr($recommend_id_at_home, 1));
					break;
				case '2':
					return array ('social_type' => 'renren', 'article_id' => substr($recommend_id_at_home, 1));
					break;
				case '3':
					return array ('social_type' => 'kaixin001', 'article_id' => substr($recommend_id_at_home, 1));
					break;
				case '4':
					return array ('social_type' => 'qqwb', 'article_id' => substr($recommend_id_at_home, 1));
					break;
				default:
					return false;
			}
		} else return false;
	}
	/**
	 * 把token记录到数据库中，根据token['uid]
	 * 
	 * @param string $social_type
	 * @param Array $token
	 * @return boolean
	 */
	public function save_token ($social_type, $token) {
		if ($token['uid'] and ($social_type=='weibo' or $social_type=='renren' or $social_type=='kaixin001' or $social_type=='qqwb')) {
			// 重构token，只保留下列字段，其余的不存储
			$token = array (
				'uid'			=> $token['uid'],
				'access_token'	=> $token['access_token'],
				'refresh_token'	=> $token['refresh_token'],
				'ctime'		=> $token['ctime'],
				'expires_in'		=> $token['expires_in'],
			);
			return $this->db->execute("
				update
					users
				set
					".$social_type."_token = '".serialize($token)."'
				where
					".$social_type."_id = '".$token['uid']."'
			");
		} else return false;
	}
	/**
	 * 在合并账号的时候用到的，之所以放在这里，是与上面的save token函数相对照，保持存储数据格式的一致
	 * 
	 * @param type $uid
	 * @param type $social_type
	 * @param type $token			  (uid, access_token, refresh_token, ctime, expires_in, name, nick)
	 * @return boolean
	 */
	public function save_token_by_uid ($uid, $social_type, $token) {
		$uid = intval($uid);
		if ($uid and $token and ($social_type=='weibo' or $social_type=='renren' or $social_type=='kaixin001' or $social_type=='qqwb')) {
			// 重构token，只保留下列字段，其余的不存储
			$token_to_db = array (
				'uid'			=> $token['uid'],
				'access_token'	=> $token['access_token'],
				'refresh_token'	=> $token['refresh_token'],
				'ctime'		=> $token['ctime'],
				'expires_in'		=> $token['expires_in'],
			);
			switch ($social_type) {
				case 'weibo':
					return $this->db->execute("
						update
							users
						set
							weibo_id			= '".$token['uid']."',
							weibo_actionname	= '".addslashes($token['name'])."',
							weibo_token		= '".  serialize($token_to_db)."'
						where
							id = ".$uid."
					");
					break;
				case 'renren':
					return $this->db->execute("
						update
							users
						set
							renren_id			= '".$token['uid']."',
							renren_actionname	= '".addslashes($token['name'])."',
							renren_token		= '".  serialize($token_to_db)."'
						where
							id = ".$uid."
					");
					break;
				case 'kaixin001':
					return $this->db->execute("
						update
							users
						set
							kaixin001_id		= '".$token['uid']."',
							kaixin001_actionname	= '".addslashes($token['name'])."',
							kaixin001_token		= '".  serialize($token_to_db)."'
						where
							id = ".$uid."
					");
					break;
				case 'qqwb':
					return $this->db->execute("
						update
							users
						set
							qqwb_id			= '".$token['uid']."',
							qqwb_actionname	= '".addslashes($token['name'])."',
							qqwb_showname		= '".addslashes($token['nick'])."',
							qqwb_token		= '".  serialize($token_to_db)."'
						where
							id = ".$uid."
					");
					break;
					
			}
		} else return false;
	}
	public function cache_write ($uid, $social_type, $flag, $data) {
		$uid			= intval($uid);
		$flag			= (preg_match('/^[\w\.-]+$/', $flag)) ? $flag : false;
		$social_type	= (preg_match('/^\w+$/', $social_type)) ? $social_type : false;
		$data			= (is_array($data)) ? serialize($data) : false;
		
		if ($uid and $flag and $data and $social_type) {
			$exist = $this->db->execute('
				select
					id
				from
					cache_social
				where
					user_id	= "'.$uid.'"			and
					social_type	= "'.$social_type.'"	and
					flag		= "'.$flag.'"
				limit
					1
			');
			if ($exist) {
				return $this->db->execute("
					update
						cache_social
					set
						data			= '".$data."',
						timestamp		= '".time()."'
					where
						id = '".$exist[0]['id']."'
				");
			} else {
				return $this->db->execute("
					insert into
						cache_social
					set
						user_id	= '".$uid."',
						social_type	= '".$social_type."',
						flag		= '".$flag."',
						data		= '".$data."',
						timestamp	= '".  time()."'
				");
			}
		} else return false;
	}
	/**
	 *
	 * @param int $uid
	 * @param string $flag
	 * @param int $expire_time		// 如果expire_time < 0，则忽略缓存过期时间，默认为 6 小时
	 * @return unknown
	 */
	public function cache_read ($uid, $social_type, $flag, $expire_time=21600) {
		$uid			= intval($uid);
		$flag 			= (preg_match('/^[\w\.-]+$/', $flag)) ? $flag : false;
		$social_type	= (preg_match('/^\w+$/', $social_type)) ? $social_type : false;
		$expire_time	= intval($expire_time);
		
		if ($uid and $flag and $social_type) {
			$exist = $this->db->execute('
				select
					*
				from
					cache_social
				where
					user_id	= "'.$uid.'"			and
					social_type	= "'.$social_type.'"	and
					flag		= "'.$flag.'"
				limit
					1
			');
			if ($exist) {
				$data = unserialize($exist[0]['data']);
				if (is_array($data)) {
					if ($expire_time < 0) {								// 忽略缓存过期时间
						return $data;
					} elseif ( (time()-$exist[0]['timestamp']) < $expire_time ) {		// 缓存没有过期，可以返回
						return $data;
					}
				} else {
					new data_error_devel('读cache的时候，解序列化的data不是数组', array('uid'=>$uid, 'flag'=>$flag, 'social_type'=>$social_type, 'execute'=>$exist), __CLASS__, __FUNCTION__, __LINE__);
				}
			}
		}
		return false;
	}
}
?>